﻿using System.Net;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace DevHub.Lib;

public static class Translate
{
    [Obsolete("Obsolete")]
    public static string TranslateFromYOUDAO(string word, string? from, string? to)
    {
        var result = "";
        if (string.IsNullOrEmpty(from) || string.IsNullOrEmpty(to)) return result;
        const string url = "https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule/";
        const string web = "fanyideskweb";
        const string key = "Y2FYu%TNSbMCxc3t2u^XT";
        var value = Convert.ToString(DateTimeOffset.Now.ToUnixTimeSeconds());
        var f = value + new Random().Next(0, 9);
        var sign = GetMd5(web + word + f + key);
        var dic = new Dictionary<string, string>
        {
            { "i", word },
            { "from", from },
            { "to", to },
            { "smartresult", "dict" },
            { "client", "fanyideskweb" },
            { "salt", f },
            { "sign", sign },
            { "lts", value },
            {
                "bv", GetMd5(
                    "5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36")
            },
            { "doctype", "json" },
            { "version", "2.1" },
            { "keyfrom", "fanyi.web" },
            { "action", "FY_BY_REALTlME" }
        };
        
        var req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
        req.Referer = "https://fanyi.youdao.com/";
        req.UserAgent =
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36";
        req.Headers.Add("Cookie",
            "OUTFOX_SEARCH_USER_ID=-2030520936@111.204.187.35; OUTFOX_SEARCH_USER_ID_NCOO=798307585.9506682; UM_distinctid=17c2157768a25e-087647b7cf38e8-581e311d-1fa400-17c2157768b8ac; P_INFO=15711476666|1632647789|1|youdao_zhiyun2018|00&99|null&null&null#bej&null#10#0|&0||15711476666; JSESSIONID=aaafZvxuue5Qk5_d9fLWx; ___rl__test__cookies=" +
            value);
        var builder = new StringBuilder();
        var i = 0;
        foreach (var item in dic)
        {
            if (i > 0)
                builder.Append('&');
            builder.Append($"{item.Key}={item.Value}");
            i++;
        }

        var data = Encoding.UTF8.GetBytes(builder.ToString());
        req.ContentLength = data.Length;
        using (var reqStream = req.GetRequestStream())
        {
            reqStream.Write(data, 0, data.Length);
            reqStream.Close();
        }

        var resp = (HttpWebResponse)req.GetResponse();
        var stream = resp.GetResponseStream();
        using (var reader = new StreamReader(stream, Encoding.UTF8))
        {
            var jo = (JObject)JsonConvert.DeserializeObject(reader.ReadToEnd())!;
            if (!jo.Value<string>("errorCode")!.Equals("0")) return result;
            var array = jo.SelectToken("translateResult")?.First().Values<string>("tgt").ToArray();
            result = string.Join("", array!);
        }

        return result;
    }

    private static string GetMd5(string encryptString)
    {
        var result = Encoding.UTF8.GetBytes(encryptString);
        var output = MD5.HashData(result);
        return BitConverter.ToString(output).Replace("-", "");
    }
}